package com.itheima.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.utils.CommonsUtils;
import com.itheima.utils.MailUtils;

/**
 * Servlet implementation class UserServlet
 */
public class UserServlet extends BaseServlet {
	
	
	//用户注销
		public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException{
			HttpSession session = request.getSession();
			//从session中将user删除
			session.removeAttribute("user");
			
			//将存储在客户端的cookie删除掉
			Cookie cookie_username = new Cookie("cookie_username","");
			cookie_username.setMaxAge(0);
			//创建存储密码的cookie
			Cookie cookie_password = new Cookie("cookie_password","");
			cookie_password.setMaxAge(0);

			response.addCookie(cookie_username);
			response.addCookie(cookie_password);
			
			
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			
		}	

	public void checkUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得用户名
				String username = request.getParameter("username");
				//后台校验用户名是否存在
				UserService userService = new UserService();
				boolean isExit =userService.checkUsername(username);
				response.getWriter().write("{\"isExit\":"+isExit+"}");
	}
	
	public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		UserService userService = new UserService();
		User user=userService.login(username,password);
		if(user!=null){
			//登录成功
			//***************判断用户是否勾选了自动登录*****************
			String autoLogin = request.getParameter("autoLogin");
			if("autoLogin".equals(autoLogin)){
				//要自动登录
				//创建存储用户名的cookie
				Cookie cookie_username = new Cookie("cookie_username",user.getUsername());
				cookie_username.setMaxAge(10*60);
				//创建存储密码的cookie
				Cookie cookie_password = new Cookie("cookie_password",user.getPassword());
				cookie_password.setMaxAge(10*60);

				response.addCookie(cookie_username);
				response.addCookie(cookie_password);

			}

			//***************************************************
			//将user对象存到session中
			request.getSession().setAttribute("user", user);

			//重定向到首页
			response.sendRedirect(request.getContextPath()+"/index.jsp");
		}else{
			request.setAttribute("loginError", "用户名或密码错误");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}
	
	
	public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String activeCode=request.getParameter("activeCode");
		response.setCharacterEncoding("UTF-8");
		UserService userService = new UserService();
		boolean isActive=userService.active(activeCode);
		if(isActive) {
			response.getWriter().write("验证成功");
		}
		else response.getWriter().write("验证失败");
	}	

	public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 response.setCharacterEncoding("UTF-8");
		 request.setCharacterEncoding("UTF-8");
		 Map<String, String[]> properties = request.getParameterMap();
		 User user = new User(); 
		 try {
			 ConvertUtils.register(new Converter() {
		            
		            public Object convert(Class type, Object value) {
		                
		                
		                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		                try {
		                    return simpleDateFormat.parse(value.toString());
		                } catch (ParseException e) {
		                    // TODO Auto-generated catch block
		                    e.printStackTrace();
		                }
		                return null;
		            }
		        }, Date.class);
			BeanUtils.populate(user, properties);
			
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//private String uid;
			user.setUid(CommonsUtils.getUUID());
			//private String telephone;
			user.setTelephone(null);
			//private int state;//是否激活
			user.setState(0);
			//private String code;//激活码
			String activeCode = CommonsUtils.getUUID();
			user.setCode(activeCode);
			
			
			//将user传递给service层
			UserService service = new UserService();
			boolean isRegisterSuccess = service.regist(user);
			//是否注册成功
			if(isRegisterSuccess){
				String emailMsg = "恭喜您注册成功，请点击下面的连接进行激活账户"
						+ "<a href='http://localhost:8080/shop/userServlet?method=active&activeCode="+activeCode+"'>"
								+ "http://localhost:8080/shop/userServlet?method=active&activeCode="+activeCode+"</a>";
				try {
					MailUtils.sendMail(user.getEmail(), emailMsg);
				} catch (MessagingException e) {
					e.printStackTrace();
				}
				//跳转到注册成功页面
				response.sendRedirect(request.getContextPath()+"/registerSuccess.jsp");
			}else{
				//跳转到失败的提示页面
				response.sendRedirect(request.getContextPath()+"/registerFail.jsp");
			}
	}
}
